package util;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;  // 添加这个导入
import java.util.Properties;

public class EmailUtil {
    // 从配置文件读取邮箱配置
    private static final Properties EMAIL_CONFIG = new Properties();
    
    static {
        try {
            EMAIL_CONFIG.load(EmailUtil.class.getClassLoader().getResourceAsStream("email.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendEmail(String to, String subject, String body) {
        final String from = EMAIL_CONFIG.getProperty("mail.from");
        final String password = EMAIL_CONFIG.getProperty("mail.password");
        String host = EMAIL_CONFIG.getProperty("mail.smtp.host");

        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);

            Transport.send(message);
            System.out.println("Email sent successfully.");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}